package com.yu.crm.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yxzz.common.helper.DataHelpers;

import java.util.ArrayList;
import java.util.List;

public class PageUtils {

    /**
     * 分页工具类
     * @param current  当前页
     * @param pageSize 每页大小
     * @param p 分页对象
     * @param list 分页集合
     * @param <T>
     * @return
     */
    public static  <T> Page<T> getPage(Long current, Long pageSize, Page<T> p, List<T> list) {
        if(DataHelpers.isEmpty(list) || list.size() == 0) {
            p.setCurrent(current);
            p.setSize(pageSize);
            p.setTotal(0L);
            p.setRecords(new ArrayList<>());
            return p;
        }
        //总条数
        int totalCount = list.size();
        String s = String.valueOf(totalCount);
        //总的页数
        Long pageCount = 0L;
        if (totalCount % pageSize > 0) {
            //数据总数和每页显示的总数不能整除的情况
            pageCount = totalCount / pageSize + 1;
        } else {
            //数据总数和每页显示的总数能整除的情况
            pageCount = totalCount / pageSize;
        }
        if (current <= pageCount) {
            if (current == 1){
                //数据总数小于每页显示的数据条数
                if (totalCount <= pageSize) {
                    //截止到总的数据条数(当前数据不足一页，按一页显示)，这样才不会出现数组越界异常
                    list = list.subList(0, totalCount);
                } else {
                    list = list.subList(0, new Long(pageSize).intValue());
                }
            }else {
                //截取起始下标
                int fromIndex = (new Long(current).intValue() - 1) * new Long(pageSize).intValue();
                //截取截止下标
                int toIndex = new Long(current).intValue() * new Long(pageSize).intValue();
                /*计算截取截止下标*/
                if ((totalCount - toIndex) % new Long(pageSize).intValue() >= 0) {
                    toIndex = new Long(current).intValue() * new Long(pageSize).intValue();
                } else {
                    toIndex = (new Long(current).intValue() - 1) * new Long(pageSize).intValue() + (totalCount % new Long(pageSize).intValue());
                }
                if (totalCount >= toIndex) {
                    list = list.subList(fromIndex, toIndex);
                }
            }
            p.setTotal(Long.parseLong(s));
        }else {
            list = null;
            p.setTotal(0L);
        }
        p.setCurrent(current);
        p.setSize(pageSize);
        p.setRecords(list);
        return p;
    }
}
